package com.demo.dao;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.demo.entity.User;
import com.demo.util.JDBCUtils;

/**
 * UserDAO：只针对User的数据库操作
 * @author david
 *
 */
public class UserDAO {
	static QueryRunner qr = new QueryRunner();
	
	//保存
	public int save(User user) {
		int nums = 0;
		try {
			nums = qr.update(JDBCUtils.getConnection(),
					"INSERT INTO t_user(username,email,sex,birth,astro,hobbies) values (?,?,?,?,?,?)",
					user.getUsername(), user.getEmail(), user.getSex(), user.getBirth(), user.getAstro(), user.getFinalHobbies());
		} catch (SQLException e) {
			System.out.println("500:新增用户异常");
			e.printStackTrace();
		}
		return nums;
	}
	
	//账户的唯一性校验(包括用户名或者email或者手机号)
	public Long checkAccount(String account, String accountType) {
		Long nums = null;
		String sqlWhere = null;
		if(accountType.equals("phone")) {
			sqlWhere = " and phone=?";
		} else if(accountType.equals("email")) {
			sqlWhere = " and email=?";
		} else {
			sqlWhere = " and username=?";
		}
		try {
			nums = qr.query(JDBCUtils.getConnection(), 
					"select count(1) as nums from t_user where 1=1 "+sqlWhere,
					new ScalarHandler<Long>(),
					account);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return nums;
	}
}
